import axios from 'axios'
import { Message} from 'element-ui';
import Bus from './bus'

let baseURL = 'http://x18tools.siruizn.com/api'
// let baseURL = 'http://192.168.1.188:5001'
const service = axios.create({
  baseURL,
  timeout: 3000
});

service.interceptors.request.use(config => {
   let token = localStorage.getItem("token");
   if(token!==undefined&&token!==""&&token!==null){
      token = "Bearer " + token;
      config.headers.Authorization= token;
    }
  return config
}, error => {
  Promise.reject(error)
})

service.interceptors.response.use(response => {
  if(response.data.code === 200){
    return response.data;
  } else {
    Message.error(response.data.msg);
    return Promise.reject(response);
  }
}, error => {
  if (error && error.response) {
    if(error.response.status === 401){
      localStorage.setItem("token","");
      Message.error("请重新登录");
      Bus.$emit("index");
      // window.location.href="/";
    }
    if(error.response.data.msg){
      Message({
          type: 'error',
          message: error.response.data.msg,
          showClose:true
      })
    }
    return Promise.reject(error.response)
  } else {
    if(error.config.url.indexOf('/user/info')===-1){
      (error);
    }
  }
  if(window.navigator.onLine){
    // Message.error("服务器出问题了");
  }else{
    if(error.config.url.indexOf('/user/login')!==-1||error.config.url.indexOf('/user/editpass')!==-1){
      Message.error("请检查本地网络");
    }
  }
  return Promise.reject(error);
})
const get = function(url,params){
  const method = "GET";
  return service({
    url,
    method,
    params
  })
}

const post = function(url,data){
  const method = "POST";
  return service({
    url,
    method,
    data
  })
}
export default {
  get,
  post
}